package com.likianta.anykey;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by Likianta_DoDoRa on 2017/11/9 0009.
 */

public class LoginActivity extends AppCompatActivity {
    
    final String DEFAULT = "44d5fz533393";
    private EditText loginPassword;
    private TextView loginWelcome;
    private Button loginOn;
    private String passwordValue;
    private SecuritySharedPreference securitySharedPreference;
    private EncryptUtil encryptUtil;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        
        // Hide edt1 bar
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        
        // Bind views
        loginPassword = (EditText) findViewById(R.id.login_password);
        loginWelcome = (TextView) findViewById(R.id.login_welcome);
        loginOn = (Button) findViewById(R.id.login_on);
        
        // Display your password to be "******"
        loginPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        
        // SecuritySharedPreference
        securitySharedPreference = new SecuritySharedPreference(getApplicationContext(), "user_login", MODE_PRIVATE); // If it not exists, android will create one instance
        final String saved_masterPassword = securitySharedPreference.getString("MasterPassword", DEFAULT); // Get your saved password, if it not exists, return DEFAULT value
        final SecuritySharedPreference.Editor editor = securitySharedPreference.edit();
        LogUtil.d("la Your loginPassword is: " + saved_masterPassword);
        
        // Switch login hello words
        switchLoginWelcome(saved_masterPassword);
        
        // loginOn button listener
        loginOn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordValue = loginPassword.getText().toString().trim();
                if (saved_masterPassword.equals(DEFAULT)) {
                    // First time use
                    editor.putString("MasterPassword", passwordValue).apply();
                    
                    Toast.makeText(LoginActivity.this, "创建成功", Toast.LENGTH_SHORT).show();
                    
                    // Go to MainActivity
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    LoginActivity.this.startActivity(intent);
                    finish();
                } else {
                    // Not first time use
                    if (passwordValue.equals(saved_masterPassword)) {
                        
                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        
                        // Go to MainActivity
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        LoginActivity.this.startActivity(intent);
                        finish();
                    } else {
                        // If your password is wrong
                        switchLoginWelcome("WRONG_CODE");
                        loginPassword.setText(""); // reset your edit bar
                        
                        // The edit bar will get focus again
                        loginPassword.setFocusableInTouchMode(true);
                        loginPassword.requestFocus();
                        
                        // and wake up your keyboard on force
                        InputMethodManager inputMethodManager = (InputMethodManager) loginPassword.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputMethodManager.showSoftInput(loginPassword, 0);
                    }
                }
            }
        });
        
        // 另外再设置一个监听软键盘输入，当输入Enter的时候，也能触发上面的登录按钮
        loginPassword.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == event.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    loginOn.callOnClick();
                    return true;
                }
                return false;
                /* 关于返回值的说明
                 * 返回值为true，表示事件已完全处理，系统无需再处理此键
                 * 返回值为false，表示事件处理过后，还要交给系统继续处理
                 * 参考此回答：https://zhidao.baidu.com/question/1430105248859125459.html
                 */
            }
        });
        
    }
    
    // Switch your hello words
    public void switchLoginWelcome(String userCode) {
        switch (userCode) {
            case DEFAULT:
                // 首次使用时的欢迎语
                loginWelcome.setText("首次使用\n请创建你的主密码");
                break;
            case "WRONG_CODE":
                // 密码输入错误时的欢迎语
                loginWelcome.setText("密码错误\n请重新登录");
                loginWelcome.setTextColor(0xFFF4297E);
                
                final AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.6f); // 不透明度的参数取值是小数，范围在0-1之间，0表示完全透明，1表示完全显示
                alphaAnimation.setDuration(500); // 动画持续时间
                alphaAnimation.setFillAfter(true); // 表示动画停留在最终完成的状态上
                loginWelcome.setAnimation(alphaAnimation);
                alphaAnimation.startNow();
                break;
        }
    }
    
    // 监听按下的按键，如果按下了返回键，则退出登录界面
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            LoginActivity.this.finish();
            return true;
        }
        return false;
    }
}

